package com.lv.config;

import com.lv.dao.UserMapper;
import com.lv.pojo.Cart;
import com.lv.service.UserService;


import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略resources 下的所有静态资源
        web.ignoring().antMatchers("/css/**","/fonts/**","/images/**","/js/**","/watch/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/toAdmin","/toWatchList").hasRole("admin")
                .antMatchers("/","/captcha/get","/captcha/check","/index","/forget","/find","/toLogin","/please","/toShop","/toRegister").permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint());


        http.formLogin().loginPage("/toLogin").failureForwardUrl("/failLogin").loginProcessingUrl("/loginCheck")
                .successHandler((request, response, authentication) -> {
                    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                    for (GrantedAuthority authority : authorities) {
                        if (authority.getAuthority().equals("ROLE_admin")){
                            response.sendRedirect("/toAdmin");
                        }
                        else{
                            String name = authentication.getName();
                            List<Cart> cartList = userMapper.getCart(name);
                            request.getSession().setAttribute("cartList", cartList);
                            request.getSession().setAttribute("isLogin", true);
                            response.sendRedirect("/index");
                        }
                    }

                });
        http.rememberMe().rememberMeParameter("remember");
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/index");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //security默认内置的验证
        auth.userDetailsService(userService);
        //也可以自定义认证方法
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

}

